package com.jhsw.roadsun.module.business.util;

import cn.hutool.core.util.StrUtil;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <b>对象锁</b>
 *
 * @author Y.sugar
 * @since 2023/4/17 17:17
 */
public class ObjLockUtil {

    /**
     * 用于存储锁对象的Map
     */
    private static final ConcurrentHashMap<String, ReentrantLock> LOCK_MAP = new ConcurrentHashMap<>();

    /**
     * 获取对象锁
     *
     * @param key 待锁 key
     * @return 取到的信息
     */
    public static ReentrantLock obtainLock(String key, Boolean fair) {
        return LOCK_MAP.computeIfAbsent(key, k -> new ReentrantLock(null != fair && fair));
    }

    /**
     * 获取对象锁
     *
     * @param key 待锁 key
     * @return 取到的信息
     */
    public static ReentrantLock obtainLock(String key) {
        return obtainLock(key, false);
    }

    /**
     * 获取对象锁
     *
     * @param template 模板值
     * @param val      当前模板唯一值
     * @return 取到的信息
     */
    public static ReentrantLock obtainLock(String template, Object val, Boolean fair) {
        return obtainLock(generatorKey(template, val), fair);
    }

    public static String generatorKey(String template, Object val) {
        return StrUtil.format(template, val);
    }

    public static void remove(String key) {
        LOCK_MAP.remove(key);
    }
}
